/**
 * 候选人，通知候选人
 */
import React from 'react';
import { Form, Card, Button, Input, Select, Upload, message, Spin, Modal, Icon } from 'antd';
import { get as getPath } from 'object-path';
import BraftEditor from 'braft-editor';
import { customUpload } from '@/utils/fileUpload';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { Attachment } from '@/pages/Mail/components';
import copy from 'copy-to-clipboard';
import useSendMail from '../useSendMail';
import { NOTICE_TYPE } from '../dictionary';
import { getCandidateInfo, getInterviewEmailTemplate, notifyMsg, queryMailTemplateListByType } from '../service';
import styles from './index.less';

const { Option } = Select;
const { confirm } = Modal;
// interview_invitation 面试邀请，interview_elimination 面试淘汰
const TYPE_MAPPING = {
    [NOTICE_TYPE.INVITE]: 'interview_invitation',
    [NOTICE_TYPE.WEED_OUT]: 'interview_elimination',
    [NOTICE_TYPE.TERMINATE]: 'employ_elimination'
};
const Notice = ({ form, location }) => {
    const { getFieldValue, setFieldsValue } = form;
    const { query } = location;
    const { candidateId, contactId, noticeType = NOTICE_TYPE.INVITE } = query;
    const { getFieldDecorator } = form;
    const [uploadFiles, setUploadFiles] = React.useState([]);
    const [previewList, setPreviewList] = React.useState([]);
    const { data: talentInfo } = useRequest(() => getCandidateInfo(candidateId), {
        refreshDeps: [candidateId],
        initialData: {},
        ...defaultFormatResult
    });

    const currentTemplateId = getFieldValue('templateId');
    const { data: info, loading } = useRequest(
        () => {
            if (currentTemplateId) {
                return getInterviewEmailTemplate(currentTemplateId, contactId, candidateId);
            }
            return Promise.resolve({ code: 10000, data: {} });
        },
        {
            refreshDeps: [currentTemplateId, contactId, candidateId],
            initialData: {},
            ...defaultFormatResult
        }
    );
    const { data: mailTemplateList } = useRequest(() => queryMailTemplateListByType(TYPE_MAPPING[noticeType]), {
        refreshDeps: [noticeType],
        initialData: [],
        ...defaultFormatResult
    });
    React.useEffect(() => {
        const id = mailTemplateList?.[0]?.id;
        if (id) setFieldsValue({ templateId: id });
    }, [mailTemplateList]);
    React.useEffect(() => {
        if (!info) {
            return;
        }
        const { emailContent, emailTitle } = info;
        if (emailContent || emailTitle) {
            setFieldsValue({
                subject: emailTitle,
                content: emailContent ? BraftEditor.createEditorState(emailContent) : BraftEditor.createEditorState('')
            });
        }
    }, [info]);

    // 生成图片预览数组
    React.useEffect(() => {
        setPreviewList([
            ...uploadFiles.map(item => ({
                uid: item.uid,
                fileName: item.name,
                fileSize: item.size
            }))
        ]);
    }, [uploadFiles]);

    // 复制内容
    const handleCopy = () => {
        copy(
            `已为您生成专属【应聘通知】链接，您可以点击链接，实时查看最新应聘进度。
        链接：https://example.com`
        );
        message.success('复制成功');
    };

    function showCopyConfirm() {
        console.log('showCopyConfirm----');
        confirm({
            title: '已通知候选人，您还可以复制【应聘通知】链接',
            content: '候选人可访问此链接，实时查看最新应聘进度',
            okText: '复制链接',
            okType: 'warning',
            icon: <Icon type="exclamation-circle" theme="filled" color="#FFA22D" />,
            // okButtonProps: {
            //     disabled: true
            // },
            cancelText: '我知道了',
            onOk() {
                handleCopy();
            },
            onCancel() {
                // console.log('Cancel');
            }
        });
    }

    // 发送候选人邮件
    const [sendParams, setSendParams] = React.useState(null); // 邮件发送内容

    const { loading: sendLoading, isSuccess, method } = useSendMail(sendParams); // 发邮件

    // 上传参数
    const uploadParam = {
        name: 'file',
        accept: '*',
        className: 'upload-list-inline',
        defaultFileList: [],
        multiple: false,
        showUploadList: false,
        fileList: uploadFiles,
        beforeUpload(file, fileList) {
            for (let i = 0; i < fileList.length; i += 1) {
                const isLimit = file.size / 1024 / 1024 < 10;
                if (!isLimit) {
                    message.error(`文件：${file.name} 超过10MB！`);
                    return false;
                }
            }
            setUploadFiles([...uploadFiles, ...fileList]);
            return false;
        }
    };

    // 删除图片
    const onRemove = e => {
        uploadFiles.splice(
            uploadFiles.findIndex(item => item.uid === e.uid),
            1
        );
        setUploadFiles([...uploadFiles]);
    };

    React.useEffect(() => {
        if (isSuccess) {
            // 添加复制链接提示
            showCopyConfirm();
            method.resetSuccess();
            pageTabUtil.goBack(-Number(getPath(query, 'r', '0')) - 1);
            try {
                if (contactId) notifyMsg({ contactId, emailSendFlag: 1 });
            } catch (error) {
                console.log(error);
            }
        }
    }, [isSuccess]);

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { email, subject, content } = values;
                const finalContent = content.toHTML().replace('a href', 'a style="color:#FFA22D" href');
                setSendParams({
                    to: email,
                    cc: '',
                    subject,
                    content: finalContent,
                    uploadFiles
                });
            }
        });
    };

    // 不允许添加尺寸大于10M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 10) {
            message.error('图片不能大于10M！');
            return false;
        }
        return true;
    };

    // 报错提示
    const handleEditorChange = editorState => {
        const html = editorState.toHTML();
        if (html.length > 20000) {
            message.error('邮件内容过多');
        }
    };

    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    const controls = [
        'undo',
        'redo',
        'separator',
        'font-size',
        'line-height',
        'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        'separator',
        'text-indent',
        'text-align',
        'separator',
        'headings',
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'media',
        'link',
        'hr',
        'separator',
        'clear'
    ];

    return (
        <PageHeaderWrapper>
            <Spin spinning={loading}>
                <Card
                    title="通知候选人"
                    bordered={false}
                    extra={
                        <BottomAction>
                            <Button
                                onClick={() => {
                                    pageTabUtil.goBack(-Number(getPath(query, 'r', '0')) - 1);
                                }}
                            >
                                取消
                            </Button>
                            <Button type="primary" onClick={handleSubmit} loading={sendLoading}>
                                确定
                            </Button>
                        </BottomAction>
                    }
                >
                    <Form className={styles.formWrap} style={{ maxWidth: '90%' }}>
                        <Form.Item label="候选人邮箱" style={{ width: '50%' }}>
                            {getFieldDecorator('email', {
                                initialValue: getPath(talentInfo, 'talentEmail', ''),
                                rules: [
                                    {
                                        required: true,
                                        message: '候选人邮箱不能为空'
                                    },
                                    {
                                        message: '请输入正确的邮箱',
                                        type: 'email'
                                    }
                                ]
                            })(<Input placeholder="请输入候选人邮箱" allowClear maxLength={100} />)}
                        </Form.Item>
                        <div style={{ display: 'flex' }}>
                            <Form.Item label="通知模版" style={{ width: '50%' }}>
                                {getFieldDecorator('templateId', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '通知模版不能为空'
                                        }
                                    ]
                                })(
                                    <Select
                                        placeholder="请选择通知模版"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {mailTemplateList &&
                                            mailTemplateList.map(item => (
                                                <Option value={item.id} key={item.id}>
                                                    {item.templateName}
                                                </Option>
                                            ))}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="邮件主题" style={{ width: '50%' }}>
                                {getFieldDecorator('subject', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '邮件主题不能为空'
                                        }
                                    ]
                                })(<Input placeholder="请输入邮件主题" allowClear maxLength={200} />)}
                            </Form.Item>
                        </div>
                        <Form.Item label="邮件内容">
                            {getFieldDecorator('content', {
                                initialValue: BraftEditor.createEditorState(null),
                                validateTrigger: 'onBlur',
                                rules: [
                                    {
                                        required: true,
                                        validator: (_, value, callback) => {
                                            if (value.isEmpty()) {
                                                callback('邮件内容不能为空');
                                            } else {
                                                callback();
                                            }
                                        },
                                        message: '邮件内容不能为空'
                                    }
                                ]
                            })(
                                <BraftEditor
                                    media={{
                                        uploadFn: myUploadFn,
                                        validateFn: myValidateFn,
                                        accepts: {
                                            image: 'image/png,image/jpeg,image/gif'
                                        }
                                    }}
                                    onChange={handleEditorChange}
                                    placeholder="请输入邮件内容"
                                    controls={controls}
                                    excludeControls={['fullscreen']}
                                    imageControls={[
                                        {
                                            onClick: block => {
                                                console.log(block);
                                            } // 指定控件点击后的回调，参数为当前图片的block对象
                                        },
                                        'align-left',
                                        'align-center',
                                        'align-right',
                                        'size',
                                        'remove'
                                    ]}
                                    contentStyle={{ height: 800 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="附件">
                            {getFieldDecorator('files')(
                                <Upload {...uploadParam}>
                                    <Button icon="upload" disabled={uploadFiles.length >= 10} style={{ marginTop: 4 }}>
                                        添加附件
                                    </Button>
                                    <div style={{ marginTop: 4 }}>
                                        支持 pdf、doc、docx、jpg、jpeg、rar 等格式的附件，单个文件大小为10MB以内
                                    </div>
                                </Upload>
                            )}
                            {previewList && previewList.length > 0 && (
                                <div style={{ marginTop: 16 }}>
                                    <Attachment attachmentList={previewList} type="del" onClick={onRemove} />
                                </div>
                            )}
                        </Form.Item>
                    </Form>
                </Card>
            </Spin>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(Notice);
